package com.eric.seo.serp;

import java.util.concurrent.Callable;

import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSONObject;
import com.eric.seo.SeoPage;

/**
 * 多线程获取SERP网页
 * @author Eric
 *
 */
class Top10 implements Callable<JSONObject> {

	private Elements html;
	private int rank;
	private String kw;

	/**
	 * 根据提供的SERP页面和排名，获取对应的SERP网页信息
	 * @param html SERP页面
	 * @param rank 排名
	 * @param kw 关键词
	 */
	public Top10(Elements html, int rank, String kw) {
		this.html = html;
		this.rank = rank;
		this.kw = kw;
	}
	
	@Override
	public JSONObject call() throws Exception {
		return getByRank(rank);
	}
	
	/**
	 * 根据提供的排名获取对应的信息
	 * @param rank 排名
	 * @return JSON 格式：<br>
	 * rank, <br>
	 * 		&nbsp seoPage, <br>
	 * 		&nbsp kwAppearances, <br>
	 * 		&nbsp url, <br>
	 * 		&nbsp title, <br>
	 * 		&nbsp description, <br>
	 */
	public JSONObject getByRank (int rank) {
		JSONObject json = new JSONObject();
		JSONObject top10J = new JSONObject();
		
		Elements rankBlock = html.select("div[id="+rank+"]");
		
		String title = rankBlock.select("h3").select("a").text();
		String description = rankBlock.select("div[class=c-abstract]").text();
		String url = rankBlock.select("h3").select("a").attr("href");
		
		SeoPage page = SeoPage.downloadSeoPage(url);
		String realUrl = null;
		if (page != null) {
			realUrl = page.url();
			json.put("seoPage", page.toString());
			json.put("kwAppearances", page.kwAppearances(kw));
		}
		
		if (realUrl != null) {
			json.put("url", realUrl);
		}else{
			json.put("url", url);
		}
		
		json.put("title", title);
		json.put("description", description);
		
		top10J.put(String.valueOf(rank), json.clone());
		return top10J;
	}

}
